package com.nuvsoft.android.nuvgamenet.example.buzzer.activities;

import java.util.LinkedList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.nuvsoft.android.nuvgamenet.GameLobby;
import com.nuvsoft.android.nuvgamenet.GameLobbyPlayerListAdapter;
import com.nuvsoft.android.nuvgamenet.GamePlayer;
import com.nuvsoft.android.nuvgamenet.R;
import com.nuvsoft.android.nuvgamenet.example.buzzer.BuzzerApplication;
import com.nuvsoft.android.nuvgamenet.net.ConnectionChangeListener;
import com.nuvsoft.android.nuvgamenet.net.TCPHandler.TCPConnection;

public class BuzzerLobby extends BuzzerActivity {
	// private static final String LOG_TAG = BuzzerLobby.class.getSimpleName();
	// private BroadcastListener playerListener;
	private ListView lv_players;
	private ListAdapter lv_adapter;
	private BuzzerApplication ba;
	private ConnectionChangeListener cl;
	private static final int MENU_START = 0;
	private List<GamePlayer> players;
	private volatile boolean isWaiting;

	// handler stuff
	private Handler uiHandler;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lobby);
		ba = (BuzzerApplication) getApplication();
		players = new LinkedList<GamePlayer>();
		isWaiting = true;
		uiHandler = new Handler();
	}

	/* Creates the menu items */
	public boolean onCreateOptionsMenu(Menu menu) {
		if (ba.getConnectionManager().getTCPHandler().isHost())
			menu.add(0, MENU_START, 0, "Start Game");
		return true;
	}

	/* Handles item selections */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_START:
			newGame();
			return true;
		}
		return false;
	}

	public void newGame() {
		ba.getConnectionManager().removeConnectionListener(cl);
		cl = null;
		ba.getConnectionManager().startGame();
		Intent myIntent = new Intent(BuzzerLobby.this, BuzzerGame.class);
		startActivity(myIntent);
		finish();
	}

	public void onStart() {
		super.onStart();
		if (!ba.getConnectionManager().getTCPHandler().isHost()) {
			joinLobby();
		} else {
			startLobbyBroadcast();
		}
	}

	@SuppressWarnings("unchecked")
	public void updateList() {
		uiHandler.post(new Runnable() {
			public void run() {
				players.clear();
				for (TCPConnection t : ba.getConnectionManager()
						.getTCPHandler().getConnections())
					if (t.getPlayerInfo() != null)
						players.add(t.getPlayerInfo());
				if (lv_adapter != null)
					((ArrayAdapter<GameLobby>) lv_adapter)
							.notifyDataSetChanged();
			}
		});
	}

	@Override
	public void onStop() {
		super.onStop();
		stopLobbyBroadcast();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			return true;
		} else {
			return false;
		}
	}

	private void joinLobby() {
		ba.getConnectionManager().startLobbyListener();
		cl = new ConnectionChangeListener() {
			@Override
			public void joinLobby() {
			}

			@Override
			public void lobbyAdded() {
			}

			@Override
			public void lobbyRemoved() {
			}

			@Override
			public void playerAdded() {
			}

			@Override
			public void playerRemoved() {
			}

			@Override
			public void startGame() {
				newGame();
			}

		};
		ba.getConnectionManager().addConnectionListener(cl);
		setupList();
	}

	public void setupList() {
		// start listening for players
		if (lv_players == null)
			lv_players = (ListView) findViewById(R.id.lv_player_list);
		if (lv_adapter == null)
			lv_adapter = new GameLobbyPlayerListAdapter(ba,
					R.layout.player_row, players);
		lv_players.setAdapter(lv_adapter);
		updateList();

		new Thread(new Runnable() {
			@Override
			public void run() {
				while (isWaiting) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					updateList();
				}
			}
		}).start();
	}

	private void startLobbyBroadcast() {
		ba.getConnectionManager().startNewLobby();
		setupList();
	}

	private void stopLobbyBroadcast() {
		ba.getConnectionManager().closeLobby();
	}

	@Override
	public boolean enableDebugLog() {
		return true;
	}

	@Override
	public boolean enableVerboseLog() {
		return true;
	}

	@Override
	public String getLogTag() {
		return BuzzerLobby.class.getSimpleName();
	}
}
